Web: https://www.meetup.com/Tel-Aviv-Deep-Learning-Bootcamp/events/241762893/
Notebooks: On GitHub
Shlomo Kashani
In [1]:
# !pip install pycuda
%reset -f
import numpy
import numpy as np
# imports
import numpy as np # numeric python lib
import matplotlib.image as mpimg # reading images to numpy arrays
import matplotlib.pyplot as plt # to plot any graph
import matplotlib.patches as mpatches # to draw a circle at the mean contour
import scipy.ndimage as ndi # to determine shape centrality
# matplotlib setup
%matplotlib inline
from pylab import rcParams
rcParams['figure.figsize'] = (6, 6) # setting default size of plots
import tensorflow as tf
print("tensorflow:" + tf.__version__)
!set "KERAS_BACKEND=tensorflow"
import numpy as np
import matplotlib.pyplot as plt
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from PIL import Image, ImageFilter
from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image
import matplotlib.pyplot as plot # Library to plot
import matplotlib.cm as colormap # Library to plot
import PIL
from PIL import Image as PILImage
import time
%matplotlib inline
import torch
import sys
print('__Python VERSION:', sys.version)
print('__pyTorch VERSION:', torch.__version__)
print('__CUDA VERSION')
from subprocess import call
# call(["nvcc", "--version"]) does not work
! nvcc --version
print('__CUDNN VERSION:', torch.backends.cudnn.version())
print('__Number CUDA Devices:', torch.cuda.device_count())
print('__Devices')
call(["nvidia-smi", "--format=csv", "--query-gpu=index,name,driver_version,memory.total,memory.used,memory.free"])
print('Active CUDA Device: GPU', torch.cuda.current_device())
print ('Available devices ', torch.cuda.device_count())
print ('Current cuda device ', torch.cuda.current_device())
from __future__ import print_function
import torch
x=torch.Tensor(3,2)
print (type(x))
print (x)
torch.from_numpy (np.zeros((3,4))).cuda()
Out[1]:
All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB images of shape (3 x H x W), where H and W are expected to be atleast 224.
The images have to be loaded in to a range of [0, 1] and then normalized using mean=[0.485, 0.456, 0.406] and std=[0.229, 0.224, 0.225]
An example of such normalization can be found in the imagenet example here: https://github.com/pytorch/examples/blob/42e5b996718797e45c46a25c55b031e6768f8440/imagenet/main.py#L89-L10119
In [2]:
import io
import requests
from PIL import Image
from torchvision import models, transforms
from torch.autograd import Variable
LABELS_URL = 'http://s3.amazonaws.com/outcome-blog/imagenet/labels.json'
# This can be any image you like
IMG_URL = '../images/nematode.jpg'
# Initialize the pre-trained model
squeeze = models.squeezenet1_1(pretrained=True)
# Image pre-processing transforms
normalize = transforms.Normalize( # Imagenet, we've done a pass on the dataset and calculated per-channel mean/std.
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
preprocess = transforms.Compose([
transforms.Scale(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize
])
In [3]:
# Create a pillow image
im = Image.open(IMG_URL)
In [4]:
print (str (type(im)))
figure = plot.figure()
figure.set_size_inches(25, 25)
imshow(im)
Out[4]:
In [5]:
img_tensor = preprocess(im)
# Add a batch dimension
img_tensor.unsqueeze_(0)
# Forward pass without activation
fc_out = squeeze(Variable(img_tensor))
# Download ImageNet labels and store them as a dict
labels = {int(key):value for (key, value)
in requests.get(LABELS_URL).json().items()}
In [6]:
# Print the label
print(labels[fc_out.data.numpy().argmax()])
In [ ]:
In [ ]:
In [ ]:
In [ ]: